<?php
defined('JPATH_BASE') or die();
jimport('joomla.utilities.simplexml');
class bookstoreXMLparser{
	private static $_Instance;

	/**
	 * Singleton
	 *
	 * @return object bookstoreXMLparser
	 */
	public static function getInstance(){
		if (!self::$_Instance){ 			
			self::$_Instance = new bookstoreXMLparser();
		}
		return self::$_Instance;
	}
	
	/**
	 * constructor
	 *
	 * @return object $this
	 */
	private function __construct(){		
		return $this;
	}
	
	/**
	 * Method to load file and return JSimpleXML object starting
	 * at node with attribute 'name' or 'id' defined by $name
	 *
	 * @param string $file path to file
	 * @param string $name name or id attribute to seek to
	 * @return object JSimpleXML
	 */
	public static function getNodes($file,$name = ''){	
		$xmlobj = new JSimpleXML();
		$xmlobj->loadFile($file);
		$nodes =& $xmlobj->document->component;
		if(empty($nodes)){return false;}
		
		if(!empty($name)){
			//look for name			
			foreach($nodes as $component){
				$name = ( $component->attributes('name') )? $component->attributes('name'):$component->attributes('id');
				if($name){
					$selected_node =& $component;
				}
			}
			$nodes =& $selected_node;
		}
		return $nodes;
	}
	
	/**
	 * NOT IMPLEMENTED
	 *
	 * @param object $node JSimpleXML NOT IMPLEMENTED
	 * @return array NOT IMPLEMENTED
	 */
	public static function toArray(&$node){
		$array = FALSE;	
		return $array;
	}
	
	/**
	 * Method for recursing JSimpleXML object
	 * 
	 * unlike bookstoreXMLparser::toObject, this is a
	 * raw object: return object with (possibly) have 
	 * may properties. All attributes are ignored!
	 *
	 * @param object $object JSimpleXML;
	 * @return object
	 */
	public static function childToObject($child){
		$descendent = $child->children();
		if(count($descendent)){
			foreach($descendent as $kid){
				$kname = $kid->name();
				$tmp->$kname = bookstoreXMLparser::childToObject($kid);	
			}		
			$robject = $tmp;	
		}else{
			$robject = $child->data();
		}
		return $robject;
	}
	
	/**
	 * Method for recursing JSimpleXML object
	 * 
	 * will return an object, who's property is named from JSimpleXML
	 * root node's 'name' or 'id' attribute.  all other attributes will be
	 * ignored!
	 *
	 * @param object $object JSimpleXML;
	 * @return object
	 */
	public static function toObject(&$object){
		//joomla configs use 'name' attribute, some devs may use 'id'
		$name = ($object->attributes('name'))? $object->attributes('name'):$object->attributes('id');
		if(!$name){
			$name = $object->name->data();
			if(!name){
				return false;
			}			
		}
		$children = $object->children();
		if(count($children)){
			foreach($children as $child){
				$cname = $child->name();
				$tmp->$cname = bookstoreXMLparser::childToObject($child);
			}
			$robject->$name = $tmp;
		}else{
			$robject->$name = $object->data();
			return $robject;
		}

		return $robject;		
	}
	
}
?>